package thread.ex.compte;

public class Compte {

	private int solde;
	private Object condOperation = new Object();
	private Object condPasArgent = new Object();
	
//	private Lock lock = new ReentrantLock();
//	private Condition condPasArgent = lock.newCondition();

	public Compte(int solde) {
		this.solde = solde;
	}

	public void retirer(int montant) {
		synchronized (condOperation) {
			if ((solde - montant) >= 0) {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				solde -= montant;
			}
		}
	}

	public void deposer(int montant) {
		synchronized (condPasArgent) {
			solde += montant;
			condPasArgent.notifyAll();
		}
	}

	public void consulter(int montant) {
		synchronized (condPasArgent) {
			while ((solde - montant) < 0) {
				try {
					System.out.println("\t\t\t" + Thread.currentThread().getId() + " pas de sous...");
					condPasArgent.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	class Titulaire extends Thread {
		private String id;

		private Titulaire(String id) {
			this.id = id;
		}

		@Override
		public void run() {
			while (true) {
				int montant = (int) (Math.random() * 50);
				System.out.println(id + " part dormir ...");
				try {
					Thread.sleep((int) (Math.random() * 1000));
					consulter(montant);
					retirer(montant);
					System.out.println(id + " a retiré : " + montant + " solde : "
							+ solde);
					System.out.println(id + " part dormir ...");
					Thread.sleep((int) (Math.random() * 1000));
					montant = (int) (Math.random() * 10);
					deposer(montant);
					System.out.println(id + " a déposé : " + montant + " solde : "
							+ solde);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {
		Compte compte = new Compte(100);
		String[] listTitutlaires = { "Pierre", "Paul", "Jacques" };
		for (String string : listTitutlaires) {
			Titulaire tito = compte.new Titulaire(string);
			tito.start();
		}
	}
}
